package com.yuyou.tas.util.tool;

import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;

import org.apache.commons.lang3.StringUtils;

import com.yuyou.tas.util.bean.ResBoolSimpleInfo;

public class SpringValidateUtil {

	
    public static ResBoolSimpleInfo<String> check(Object obj) {
    	ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
    	res.setSuccess(true);
        if (null == obj) {
            return res;
        }
        Set<ConstraintViolation<Object>> validResult = Validation.buildDefaultValidatorFactory().getValidator().validate(obj);
        if (null != validResult && validResult.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Iterator<ConstraintViolation<Object>> iterator = validResult.iterator(); iterator.hasNext();) {
                ConstraintViolation<Object> constraintViolation = (ConstraintViolation<Object>) iterator.next();
                if(StringUtils.isNotBlank(constraintViolation.getMessage())) {
                    sb.append(constraintViolation.getMessage()).append("、");
                } else {
                    sb.append(constraintViolation.getPropertyPath().toString()).append("不合法、");
                }
            }
            if (sb.lastIndexOf("、") == sb.length() - 1) {
                sb.delete(sb.length() - 1, sb.length());
            }
            res.setSuccess(false);
            res.setMessage(sb.toString());
            return res;
        }
        return res;
    }
	
}
